<?php

/*
+--------------------------------------------------------------------------
|   Invision Power Board
|   =============================================
|   by Matthew Mecham
|   (c) 2001 - 2006 Invision Power Services, Inc.
|   
|   =============================================
|   
|   
+---------------------------------------------------------------------------
|   > $Date: 2007-05-02 17:29:12 -0400 (Wed, 02 May 2007) $
|   > $Revision: 959 $
|   > $Author: BabyWolf $
+---------------------------------------------------------------------------
|
|   > Access the dkm_bank files
|   > Module written by BabyWolf
|   > Date started: 07th February 2009
|
|	> Module Version Number: 1.0.0
|   > DBA Checked: Sat 07 Feb 2009
|   > Quality Checked: Sat 07 Feb. 2009
+--------------------------------------------------------------------------
*/


if ( ! defined( 'IN_IPB' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
	exit();
}

class dkm_regportal
{
	# Classes
	var $ipsclass;
	
	# Others
    var $output     = "";
    var $page_title = "";
    var $nav        = array();
    var $html       = "";

	/*-------------------------------------------------------------------------*/
	// Auto run
	/*-------------------------------------------------------------------------*/
	
    function auto_run()
    {
    	//-----------------------------------------
    	// Require the HTML and language modules
    	//-----------------------------------------
		
		$this->ipsclass->load_language('lang_regportal');
    	$this->ipsclass->load_template('skin_regportal');

    	
    	$this->base_url  = $this->ipsclass->base_url."act=regportal";
    	$this->base_url_nosess = "{$this->ipsclass->vars['board_url']}/index.{$this->ipsclass->vars['php_ext']}";
    	
   		//-----------------------------------------
    	// Get the emailer module
		//-----------------------------------------
		
		require ROOT_PATH."sources/classes/class_email.php";
		
		$this->email = new emailer();
		$this->email->ipsclass =& $this->ipsclass;
		$this->email->email_init();
		
		if ( USE_MODULES == 1 )
		{
			require ROOT_PATH."modules/ipb_member_sync.php";
			
			$this->modules = new ipb_member_sync();
			$this->modules->ipsclass =& $this->ipsclass;
		}
		
    	//-----------------------------------------
    	// What to do?
    	//-----------------------------------------
    
    	switch($this->ipsclass->input['CODE'])
    	{
			case 'process': // Create account
				$this->regportal_process();
				break;			
			case 'termsread':// Read Terms
				$this->show_terms_read();
				break;				
			case 'result':
				$this->show_search_result();
				break;    		
			case 'import_members':
				$this->import_members();
				break;
			case 'fix_member_data':
				$this->fix_member_data();
				break;  
			case 'wg':
				$this->my_show_page_cpanel();
				break;  	
			case 'pf':
				$this->my_show_page_profile();
				break;
                        case 'sr':
                            $this->my_show_page_search();
                            break;
                        case 'edit-pro-info':
                            $this->my_ajax_edit_profile();
                            //exit();
                            break;
                        case 'change-pass':
                            $this->change_password();
                            break;
                        case 'change-pic':
                            $this->change_pic();
                            break;
                        case 'delete-pic':
                            $this->delete_pic();
                            break;
                            
			default:
				//$this->my_show_page();
				//$this->show_page();
				
				$this->my_show_page();
				return;
				break;
    	}   
    	
    	//-----------------------------------------
    	// If we have any HTML to print, do so...
    	//-----------------------------------------
    	
    	$this->ipsclass->print->add_output("$this->output");    
        $this->ipsclass->print->do_output( array( 'TITLE' => $this->page_title, 'JS' => 0, 'NAV' => $this->nav ) );
        
 	}
 	
 	function fix_member_data() {
 		$start = intval($_GET['num']);
 		$vol = 1;
 		
 		if($start>=13226) { echo "success"; exit();}
 		if($start==$_GET['max']) exit();
		
 		$this->ipsclass->DB->simple_construct(array('select'	=> '*',
 												'from'		=> 'members',
 												'where'		=> 'maple_check=2',
 												'order'		=> 'id',
 												'limit'		=> array($start,$vol)
 												)
 											);
 		
 		$this->ipsclass->DB->simple_exec();
 		
 		//-----------------------------------------
		// Custom profile field stuff
		//-----------------------------------------
		
		require_once( ROOT_PATH.'sources/classes/class_custom_fields.php' );
    	$fields = new custom_fields( $this->ipsclass->DB );
    
    	$fields->cache_data  = $this->ipsclass->cache['profilefields'];
    	
    	$fields->init_data();
    	$fields->parse_to_save( 1 );
    	
		foreach( $fields->out_fields as $_field => $_data )
		{
			$this->ipsclass->DB->force_data_type[ $_field ] = 'string';
		}
		
 		error_reporting(E_ALL);
 		while($result = $this->ipsclass->DB->fetch_row()) {
			$fields->out_fields['member_id'] = $result['id'];
			$this->ipsclass->DB->do_insert( 'pfields_content', $fields->out_fields );	
			echo "Inserted for member ".$result['name']." <br />";
 		}
 		
 		echo "Completed ".$start;
 		$url = $this->ipsclass->vars['board_url']."/index.php?act=regportal&CODE=fix_member_data&num=".($start+$vol)."&max=".$_GET['max'];
		
 		header( "refresh:1;url=".$url );
  		echo 'You\'ll be redirected in about 1 secs. If not, click <a href="wherever.php">here</a>.';
		exit();
 	}
 	
 	function import_members() {
 		$start = intval($_GET['num']);
 		$vol = 1;
 		
 		if($start>=13227) { echo "success"; exit();}
 		if($start==$_GET['max']) exit();
		
 		$this->ipsclass->DB->simple_construct(array('select'	=> '*',
 												'from'		=> 'accounts',
 												'order'		=> 'id',
 												'limit'		=> array($start,$vol)
 												)
 											);
 		
 		$this->ipsclass->DB->simple_exec();
 		error_reporting(E_ALL);
 		$count = $start+1;
 		while($result = $this->ipsclass->DB->fetch_row()) {
 			echo $name = $result['name'];
 			echo $pass = "maplenopass";
			echo $email = "maple".$count."@even.vn";
			$this->create_account($name, $pass, $email);
			
			echo "Inserted ".$name." <br />";
			echo $count++;
 		}
 		
 		echo "Completed ".$start;
 		$url = $this->ipsclass->vars['board_url']."/index.php?act=regportal&CODE=import_members&num=".($start+$vol)."&max=".$_GET['max'];
		
 		header( "refresh:1;url=".$url );
  		echo 'You\'ll be redirected in about 1 secs. If not, click <a href="wherever.php">here</a>.';
		exit();
 	}
 	
        
        /*
         * Chung nguyen huu
         * Function: edit profile
         * Date: 2011/09/09
         * 
         */
        //$display_name = "", $real_name = "", $email = "", $day = -1, $month = -1, $year = -1, $job = "", $hobby= ""
        function my_ajax_edit_profile(){
           
            if( empty ($this->ipsclass->input['txt_display_name']) ){
                echo "display_name";
                exit();
            }
            if(empty ($this->ipsclass->input['txtemail'])){
                echo "email";
                exit();
            }
            //var_dump($this->ipsclass->member);
            
            $member = array(
                
                email => $this->ipsclass->input['txtemail'],
                bday_day => intval( $this->ipsclass->member['day'] ),
                bday_month => intval($this->ipsclass->input['month']),
                bday_year => intval($this->ipsclass->input['year']) 
            );
            
            $this->save_member('members', $member, ' id = ' . intval($this->ipsclass->member['id']));
            /*
             * 
             * Update table member_extra
             * 
             */
            if ( (strlen($this->ipsclass->input['txthobby']) > $this->ipsclass->vars['max_interest_length']) and ($this->ipsclass->vars['max_interest_length']) )
            {
                    $this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'int_too_long' ) );
                    echo "hobby";
                    exit();
            }
            $member_extra = array(
                interests => $this->ipsclass->input['txthobby']
            );
            $this->save_member("member_extra", $member_extra, ' id = ' . intval($this->ipsclass->member['id']));
            
            /*
             * update table pfields_content
             * 
             */
            $real_name = trim($this->ipsclass->input['txtrealname']);
            
            $keywords = preg_split ("/[\s ]+/", $real_name);
            
            $first_name = count($keywords) >=1 ? $keywords[0] : "";
            $last_name = "";
            if(sizeof($keywords) >= 2){
                for ($index = 1; $index < count($keywords); $index++) {
                    $last_name .= $keywords[$index];
                    if($index < count($keywords) - 1){
                        $last_name .= " ";
                    }
                }
            }
            //echo $first_name . "@" . $last_name;
            //exit();
            
            $pfields_content = array(
                field_14 => $first_name,
                field_15 => $last_name,
                field_16 => $this->ipsclass->input['txtjob']
            );
            $this->save_member("pfields_content", $pfields_content, ' member_id = ' . $this->ipsclass->member['id']);
             //update gender
            $_gender = $this->ipsclass->input['gender'] == 'male' ? 'male' : ( $this->ipsclass->input['gender'] == 'female' ? 'female' : '' );
            //echo $_gender;exit();
            
            //check profile id
            if($_gender == null || $_gender == ""){
                $this->ipsclass->DB->do_insert( 'profile_portal', array( 'pp_gender' => $_gender, 'pp_member_id' => $this->ipsclass->member['id'] ) );
            }else{
                $this->save_member("profile_portal", array('pp_gender'=>$_gender), ' pp_member_id = ' . $this->ipsclass->member['id']);
            }
            
            /*
             * update table members_converge
             * 
             */
            
            $this->ipsclass->DB->do_update('members_converge', array('converge_email' => $this->ipsclass->member['email']), ' converge_id = ' . $this->ipsclass->member['id']);
            //print_r($this->ipsclass->member);
            echo "success";
            exit();
            
        }
        /*
         * 
         * CHung nguyen huu
         * change member password
         * 2011/09/10
         */
        function change_password(){
            //check validate
            //current pass
            if( empty ($this->ipsclass->input['txtpasscurent']) ){
                echo "current_pass";
                exit();
            }
            
            //new pass
            if(empty($this->ipsclass->input['txtpassnew1'])){
                echo "new_pass";
                exit();
            }
            //check new pass
            if(empty($this->ipsclass->input['txtpassnew2'])){
                echo "check_new_pass";
                exit();
            }
            
            //start create password
            $salt     = $this->ipsclass->converge->generate_password_salt(5);
            $passhash = $this->ipsclass->converge->generate_compiled_passhash( $salt, md5($this->ipsclass->input['txtpassnew1']));
            $converge_array = array( //'converge_email'     => $in_email,
                                     'converge_joined'    => time(),
                                     'converge_pass_hash' => $passhash,
                                     'converge_pass_salt' => str_replace( '\\', "\\\\", $salt )
                     );
             
            //$this->ipsclass->DB->do_update('members_converge', $converge_array, ' converge_id = ' . $this->ipsclass->member['id']);
                    print_r($this->ipsclass->member);
                     exit();
        }

        /*
         * Chung Nguyen Huu
         * change picture
         * 2011/09/10
         */
        function change_pic(){
            //check new pass
            if(empty($this->ipsclass->input['updatepic'])){
                echo "check_new_pass";
                exit();
            }
            print_r($this->ipsclass->member);
            exit();
        }
        /*
         * Chung Nguyen Huu
         * delete picture
         * 2011/09/10
         */
        function delete_pic(){
            //check new pass
            if(empty($this->ipsclass->input['showPic'])){
                //echo "check_new_pass";
                //exit();
            }
            
        }
        /*
         * Chung nguyen huu
         * Save data to database
         * 
         */
        function save_member($table_name,$member, $where){
            $this->ipsclass->DB->do_update($table_name, $member, $where);
//            $this->ipsclass->DB->build_query( array( 'update' => " members name = , email = , email = , bday_day = , bday_month = , bday_year = ",
//                 //'from'   => 'members',
//                 'where'  => "members_l_display_name='".strtolower($in_username)."'",
//                 'limit'  => array( 0,1 ) ) );
//													 
//            $this->ipsclass->DB->exec_query();
        }
 	function create_account($username="", $password="", $email="") {
 	//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$in_username = str_replace( '|', '&#124;' , trim($username) );
		$in_username = trim( preg_replace( "/\s{2,}/", " ", $in_username ) );
		$in_password = trim($password);
		$in_email    = trim(strtolower($email));
		
		$members_display_name = $in_username;
			
		if ( $this->ipsclass->vars['strip_space_chr'] )
    	{
    		// use hexdec to convert between '0xAD' and chr
			$in_username          = str_replace( chr(160), ' ', $in_username );
			$in_username          = str_replace( chr(173), ' ', $in_username );
			$in_username          = str_replace( chr(240), ' ', $in_username );
			$members_display_name = str_replace( chr(160), ' ', $members_display_name );
			$members_display_name = str_replace( chr(173), ' ', $members_display_name );
			$members_display_name = str_replace( chr(240), ' ', $members_display_name );
		}
					
		$member = array(
						 'name'                   => $in_username,
						 'members_l_username'     => strtolower( $in_username ),
						 'members_display_name'   => $members_display_name ? $members_display_name : $in_username,
						 'members_l_display_name' => strtolower( $members_display_name ? $members_display_name : $in_username ),
						 'member_login_key'       => $this->ipsclass->converge->generate_auto_log_in_key(),
						 'email'                  => $in_email,
						 'mgroup'                 => 3,
						 'posts'                  => 0,
						 'joined'                 => time(),
						 'ip_address'             => $this->ipsclass->ip_address,
						 'time_offset'            => $this->ipsclass->vars['time_offset'],
						 'view_sigs'              => 1,
						 'coppa_user'			  => 0,
						 'email_pm'               => 1,
						 'view_img'               => 1,
						 'view_avs'               => 1,
						 'restrict_post'          => 0,
						 'view_pop'               => 1,
						 'msg_total'              => 0,
						 'new_msg'                => 0,
						 'members_editor_choice'  => $this->ipsclass->vars['ips_default_editor'],
						 'language'               => $this->ipsclass->vars['default_language'],
						 'maple_check'			  => 2 
					   );
		
		$salt     = $this->ipsclass->converge->generate_password_salt(5);
		$passhash = $this->ipsclass->converge->generate_compiled_passhash( $salt, md5($in_password) );
					   
		$converge_array = array( 'converge_email'     => $in_email,
						   		 'converge_joined'    => time(),
						   		 'converge_pass_hash' => $passhash,
						   		 'converge_pass_salt' => str_replace( '\\', "\\\\", $salt )
						 );
		
		
		//-----------------------------------------
		// Insert: CONVERGE
		//-----------------------------------------
		
		$this->ipsclass->DB->do_insert( 'members_converge', $converge_array );
		
		//-----------------------------------------
		// Get converges auto_increment user_id
		//-----------------------------------------
		
		$member_id    = $this->ipsclass->DB->get_insert_id();
		$member['id'] = $member_id;
		
		//-----------------------------------------
		// Insert: MEMBERS
		//-----------------------------------------
		
		$this->ipsclass->DB->force_data_type = array( 'name' => 'string', 'members_l_username' => 'string', 'members_display_name' => 'string', 'members_l_display_name' => 'string' );
		
		$this->ipsclass->DB->do_insert( 'members', $member );
		
		//-----------------------------------------
		// Insert: MEMBER EXTRA
		//-----------------------------------------
		
		$this->ipsclass->DB->do_insert( 'member_extra', array( 'id'        => $member_id,
															   'vdirs'     => 'in:Inbox|sent:Sent Items',
															   'interests' => '',
															   'signature' => '' ) );
		
		//-----------------------------------------
		// Stats
		//-----------------------------------------
		
		$this->ipsclass->init_load_cache( array( 'stats' ) );
		
		$this->ipsclass->cache['stats']['last_mem_name'] = $members_display_name ? $members_display_name : $in_username;
		$this->ipsclass->cache['stats']['last_mem_id']   = $member['id'];
		// Added by BabyWolf
		$this->ipsclass->cache['stats']['last_mem_username']   = $in_username;
		
		$r = $this->ipsclass->DB->build_and_exec_query( array( 'select' => 'count(id) as members', 'from' => 'members', 'where' => "mgroup <> '".$this->ipsclass->vars['auth_group']."'" ) );

		$this->ipsclass->cache['stats']['mem_count'] = intval($r['members']);		
		
		if ( count($this->ipsclass->cache['stats']) > 0 )
		{
			$this->ipsclass->update_cache( array( 'name' => 'stats', 'array' => 1, 'deletefirst' => 1 ) );
		}
		
		
		//-----------------------------------------
		// Log and bog?
		//-----------------------------------------
		             
		//$this->ipsclass->admin->save_log("Created new member account for '{$this->ipsclass->input['name']}'");
 	}
 	
 	function regportal_process() {
 		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
 		// First get parameters from session
 		$this->ipsclass->input = array_merge($this->ipsclass->input,$_SESSION);
		
 		$form_errors          = array();
		$coppa                = ($this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
		$in_username          = str_replace( '|', '&#124;' , $this->ipsclass->input['UserName'] );
		$in_password          = trim($this->ipsclass->input['PassWord']);
		$in_email             = strtolower( trim($this->ipsclass->input['EmailAddress']) );
		$banfilters           = array();
		$members_display_name = trim( $this->ipsclass->input['members_display_name'] );
		
 		//-----------------------------------------
		// Did we agree to the t&c?
		//-----------------------------------------
			
		if ( ! $this->ipsclass->input['agree_to_terms'] )
		{
			$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'reg_no_agree', 'EXTRA' => $this->ipsclass->base_url ) );
		}
			
 		//-----------------------------------------
		// Check the reg_code
		//-----------------------------------------
		$reg_code_err_msg = "";
		
		if ($this->ipsclass->vars['bot_antispam'])
		{
			if ( $this->ipsclass->input['regid'] == "" )
			{
				$reg_code_err_msg = $this->ipsclass->lang['err_reg_code'];
			}
			else
			{
				$this->ipsclass->DB->build_query( array( 'select' => '*',
															  'from'   => 'reg_antispam',
															  'where'  => "regid='".trim($this->ipsclass->txt_alphanumerical_clean($this->ipsclass->input['regid']))."'"
													 )      );
									 
				$this->ipsclass->DB->exec_query();
				
				if ( ! $row = $this->ipsclass->DB->fetch_row() )
				{
					$reg_code_err_msg = $this->ipsclass->lang['err_reg_code'];
				}
				else if ( trim( $this->ipsclass->txt_alphanumerical_clean($this->ipsclass->input['reg_code']) ) != $row['regcode'] )
				{
					$reg_code_err_msg = $this->ipsclass->lang['err_reg_code'];
				}
				
				$this->ipsclass->DB->do_delete( 'reg_antispam', "regid='".trim($this->ipsclass->txt_alphanumerical_clean($this->ipsclass->input['regid']))."'" );
			}
		}
		
		//-----------------------------------------
		// CHECK 2: Any errors (duplicate names, etc)?
		//-----------------------------------------
		
		if ( $reg_code_err_msg )
		{
			$this->show_terms_read( $reg_code_err_msg );
			return;
		}
		
		//-----------------------------------------
		// Build up the hashes
		//-----------------------------------------
		
		$mem_group = $this->ipsclass->vars['member_group'];
		
		//-----------------------------------------
		// Are we asking the member or admin to preview?
		//-----------------------------------------
		
		if ( $this->ipsclass->vars['reg_auth_type'] )
		{
			$mem_group = $this->ipsclass->vars['auth_group'];
		}
		else if ($coppa == 1)
		{
			$mem_group = $this->ipsclass->vars['auth_group'];
		}
		else if ( $this->ipsclass->vars['subsm_enforce'] )
		{
			$mem_group = $this->ipsclass->vars['subsm_nopkg_group'];
		}
		
		$_mke_time   = ( $this->ipsclass->vars['login_key_expire'] ) ? ( time() + ( intval($this->ipsclass->vars['login_key_expire']) * 86400 ) ) : 0;
		
 		//-----------------------------------------
		// make sure that either we entered
		// all calendar fields, or we left them
		// all blank
		//-----------------------------------------
		
		$c_cnt = 0;
		
		foreach ( array('day','month','year') as $v )
		{
			if ( ! empty($this->ipsclass->input[$v] ) )
			{
				$c_cnt++;
			}
		}
		
		if ( ($c_cnt > 0) and ($c_cnt != 3) )
		{
			$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'calendar_not_all' ) );
		}
		else if( ($c_cnt > 0) and ($c_cnt == 3) )
		{
			//-----------------------------------------
			// Make sure it's a legal date
			//-----------------------------------------
			
			$_year = $this->ipsclass->input['year'] ? $this->ipsclass->input['year'] : 1999;
			
			if ( ! checkdate( $this->ipsclass->input['month'], $this->ipsclass->input['day'], $_year ) )
			{
				$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'ucp_birthday_legal_date' ) );
			}
		}
		
		$member = array(
						 'name'                   => $in_username,
						 'members_l_username'     => strtolower( $in_username ),
						 'members_display_name'   => $this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username,
						 'members_l_display_name' => strtolower( $this->ipsclass->vars['auth_allow_dnames'] ? $members_display_name : $in_username ),
						 'member_login_key'       => $this->ipsclass->converge->generate_auto_log_in_key(),
						 'member_login_key_expire' => $_mke_time,
						 'email'                  => $in_email,
						 'mgroup'                 => $mem_group,
						 'posts'                  => 0,
						 'joined'                 => time(),
						 'ip_address'             => $this->ipsclass->ip_address,
						 'time_offset'            => $this->ipsclass->input['time_offset'],
						 'view_sigs'              => 1,
						 'email_pm'               => 1,
						 'view_img'               => 1,
						 'view_avs'               => 1,
						 'restrict_post'          => 0,
						 'view_pop'               => 1,
						 'msg_total'              => 0,
						 'new_msg'                => 0,
						 'coppa_user'             => $coppa,
						 'language'               => $this->ipsclass->vars['default_language'],
						 'members_auto_dst'       => 1,
						 'members_editor_choice'  => $this->ipsclass->vars['ips_default_editor'],
						 'allow_admin_mails'      => 1,
						 'hide_email'             => 1,
						 'subs_pkg_chosen'        => intval( $this->ipsclass->input['subspackage']),
						 'bday_day'    			  => $this->ipsclass->input['day'],
						 'bday_month'  			  => $this->ipsclass->input['month'],
						 'bday_year'   			  => $this->ipsclass->input['year'], 
						 'members_country'   	  => substr($this->ipsclass->input['country'],strpos($this->ipsclass->input['country'],'|')+1),
						 'members_city'			  => substr($this->ipsclass->input['city'],strpos($this->ipsclass->input['city'],'|')+1),
						 'members_district' 	  => substr($this->ipsclass->input['district'],strpos($this->ipsclass->input['district'],'|')+1),
						 'members_ward'			  => $this->ipsclass->input['ward'],
						 'members_address'		  => $this->ipsclass->input['address']
					   );					  
		
		//-----------------------------------------
		// Insert: CONVERGE
		//-----------------------------------------
		
		//print_r ($member);
		//exit();
		
		$salt     = $this->ipsclass->converge->generate_password_salt(5);
		$passhash = $this->ipsclass->converge->generate_compiled_passhash( $salt, md5($in_password) );
					   
		$converge = array( 'converge_email'     => $in_email,
						   'converge_joined'    => time(),
						   'converge_pass_hash' => $passhash,
						   'converge_pass_salt' => str_replace( '\\', "\\\\", $salt )
						 );
				
		//-----------------------------------------
		// Add Converge: Member
		//-----------------------------------------
		//-----------------------------------------
    	// Load handler...
    	//-----------------------------------------
    	
    	require_once( ROOT_PATH.'sources/handlers/han_login.php' );
    	$this->han_login           =  new han_login();
    	$this->han_login->ipsclass =& $this->ipsclass;
    	$this->han_login->init();
    	
   		$this->han_login->create_account( array(	'email'			=> $member['email'],
   													'joined'		=> $member['joined'],
   													'password'		=> $in_password,
   													'ip_address'	=> $this->ipsclass->ip_address
   										)		);
   										
		//echo 'RETURN CODE : '.$this->han_login->return_code;
		//exit();

		if( $this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'SUCCESS' )
		{
			$this->ipsclass->Error( array( 'LEVEL' => 5, 'MSG' => 'han_login_create_failed', 'EXTRA' => $this->han_login->return_details ? $this->han_login->return_details : $this->han_login->return_code ) );
		}
		
		$this->ipsclass->DB->do_insert( 'members_converge', $converge );
		
		//-----------------------------------------
		// Get converges auto_increment user_id
		//-----------------------------------------
		
		$member_id    = $this->ipsclass->DB->get_insert_id();
		$member['id'] = $member_id;
		
		//-----------------------------------------
		// Insert: MEMBERS
		//-----------------------------------------
		$this->ipsclass->DB->force_data_type = array( 'name' => 'string', 'members_display_name' => 'string', 'members_l_username' => 'string', 'members_l_display_name' => 'string' );
									  
		$this->ipsclass->DB->do_insert( 'members', $member );
		
		//-----------------------------------------
		// Insert: MEMBER EXTRA
		//-----------------------------------------
		$this->ipsclass->DB->do_insert( 'member_extra', array( 'id'        => $member_id,
															   'vdirs'     => 'in:Inbox|sent:Sent Items',
															   'interests' => '',
															   'signature' => '',
															   'location' => $this->ipsclass->input['siteLocation'] ) );
		
		// Insert chosen gender
		$_gender = $this->ipsclass->input['gender'] == 'male' ? 'male' : ( $this->ipsclass->input['gender'] == 'female' ? 'female' : '' );
		$this->ipsclass->DB->do_insert( 'profile_portal', array( 'pp_gender' => $_gender, 'pp_member_id' => $member['id'] ) );
		
		//-----------------------------------------
		// Insert into the custom profile fields DB
		//-----------------------------------------
		
		// Ensure deleted members profile fields are removed.
		
		$this->ipsclass->DB->do_delete( 'pfields_content', 'member_id='.$member['id'] );
		
		$this->ipsclass->DB->force_data_type = array();
		
		//-----------------------------------------
		// Custom profile field stuff
		//-----------------------------------------
		
		require_once( ROOT_PATH.'sources/classes/class_custom_fields.php' );
    	$fields = new custom_fields( $this->ipsclass->DB );
    
    	$fields->cache_data  = $this->ipsclass->cache['profilefields'];
    	
    	$fields->init_data();
    	$fields->parse_to_save( 1 );
    	
		foreach( $fields->out_fields as $_field => $_data )
		{
			$this->ipsclass->DB->force_data_type[ $_field ] = 'string';
		}

		$fields->out_fields['member_id'] = $member['id'];
				
		$this->ipsclass->DB->do_insert( 'pfields_content', $fields->out_fields );
				
		//-----------------------------------------
		// Use modules?
		//-----------------------------------------
		//echo 'USE MODULES : '.USE_MODULES;
		//exit();
		//exit();
		
		if ( USE_MODULES == 1 )
		{
			
			echo 'ha ha USE_MODULES';
			
			$this->modules->register_class($this);
			
			echo 'under USE_MODULES';
			
			$member['password'] = trim($this->ipsclass->input['PassWord']);
			
    		$this->modules->on_create_account($member);
    		
    		if ( $this->modules->error == 1 )
    		{
				echo 'in modules error';
				//************************
				// Updated by tuanhnm
				// on 06/08/2011
				// *********************
				$url = "http://www.worldgames.vn/index.php?act=regportal&&CODE=wg";
			//$this->ipsclass->print->redirect_screen( $this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12' );
				$this->ipsclass->print->redirect_screen($url);
				
    			return;
    		}
    		
    		//echo 'in USE_MODULES';
    		//exit();
    		
    		//********
    		// Updatedby tuanhnm
    		// fixed tempature, not remove please
    		//*********
    		$url = "www.worldgames.vn/index.php?act=regportal&&CODE=wg";
			//$this->ipsclass->print->redirect_screen( $this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12' );
			$this->ipsclass->boink_it($this->ipsclass->base_url.'&act=regportal&&CODE=wg');
			return;
    		
    		$member['password'] = "";
   		}
   		
		//-----------------------------------------
		// Validation key
		//-----------------------------------------
		
		$validate_key = md5( $this->ipsclass->make_password() . time() );
		$time         = time();
		
		if ($coppa != 1)
		{
			if ( ($this->ipsclass->vars['reg_auth_type'] == 'user' ) or
				 ($this->ipsclass->vars['reg_auth_type'] == 'admin') or
				 ($this->ipsclass->vars['reg_auth_type'] == 'admin_user') )
			{
				//-----------------------------------------
				// We want to validate all reg's via email,
				// after email verificiation has taken place,
				// we restore their previous group and remove the validate_key
				//-----------------------------------------
				
				$this->ipsclass->DB->do_insert( 'validating', array (
													  'vid'         => $validate_key,
													  'member_id'   => $member['id'],
													  'real_group'  => $this->ipsclass->vars['subsm_enforce'] ? $this->ipsclass->vars['subsm_nopkg_group'] : $this->ipsclass->vars['member_group'],
													  'temp_group'  => $this->ipsclass->vars['auth_group'],
													  'entry_date'  => $time,
													  'coppa_user'  => $coppa,
													  'new_reg'     => 1,
													  'ip_address'  => $member['ip_address']
											)       );
				
				
				if ( $this->ipsclass->vars['reg_auth_type'] == 'user' OR $this->ipsclass->vars['reg_auth_type'] == 'admin_user' )
				{
					$this->email->get_template("reg_validate");
					
					$this->email->build_message( array(
														'THE_LINK'     => $this->base_url_nosess."?act=Reg&CODE=03&uid=".urlencode($member_id)."&aid=".urlencode($validate_key),
														'NAME'         => $member['members_display_name'],
														'MAN_LINK'     => $this->base_url_nosess."?act=Reg&CODE=05",
														'EMAIL'        => $member['email'],
														'ID'           => $member_id,
														'CODE'         => $validate_key,
													  )
												);
												
					$this->email->subject = $this->ipsclass->lang['new_registration_email'].$this->ipsclass->vars['board_name'];
					$this->email->to      = $member['email'];
					
					$this->email->send_mail();
					
					$this->output     = $this->ipsclass->compiled_templates['skin_regportal']->show_authorise( $member );
					
				}
				else if ( $this->ipsclass->vars['reg_auth_type'] == 'admin' )
				{
					$this->output     = $this->ipsclass->compiled_templates['skin_regportal']->show_preview( $member );
				}
				
				if ($this->ipsclass->vars['new_reg_notify'])
				{
					
					$date = $this->ipsclass->get_date( time(), 'LONG', 1 );
					
					$this->email->get_template("admin_newuser");
				
					$this->email->build_message( array(
														'DATE'         => $date,
														'MEMBER_NAME'  => $member['members_display_name'],
													  )
												);
												
					$this->email->subject = $this->ipsclass->lang['new_registration_email1'].$this->ipsclass->vars['board_name'];
					$this->email->to      = $this->ipsclass->vars['email_in'];
					$this->email->send_mail();
				}
				
				$this->page_title = $this->ipsclass->lang['reg_success'];
				
				$this->nav        = array( $this->ipsclass->lang['nav_reg'] );
			}
	
			else
			{
				//-----------------------------------------
				// We don't want to preview, or get them to validate via email.
				//-----------------------------------------
							 
				$this->ipsclass->cache['stats']['last_mem_name'] = $member['members_display_name'];
				$this->ipsclass->cache['stats']['last_mem_id']   = $member['id'];
				// Added by BabyWolf
				$this->ipsclass->cache['stats']['last_mem_username']   = $member['name'];
				// Updated by BabyWolf
				//$this->ipsclass->cache['stats']['mem_count']    += 1;
				$this->ipsclass->cache['stats']['mem_count']    = $member['id'];
				
				$this->ipsclass->update_cache(  array( 'name' => 'stats', 'array' => 1, 'deletefirst' => 0 ) );
				
				if ($this->ipsclass->vars['new_reg_notify'])
				{
					$date = $this->ipsclass->get_date( time(), 'LONG', 1 );
					
					$this->email->get_template("admin_newuser");
				
					$this->email->build_message( array(
														'DATE'         => $date,
														'MEMBER_NAME'  => $member['members_display_name'],
													  )
												);
												
					$this->email->subject = $this->ipsclass->lang['new_registration_email1'].$this->ipsclass->vars['board_name'];
					$this->email->to      = $this->ipsclass->vars['email_in'];
					$this->email->send_mail();
				}
				
				$this->ipsclass->no_print_header = 0;
				
				$this->ipsclass->my_setcookie("pass_hash"   , $member['member_login_key'], 1);
				$this->ipsclass->my_setcookie("member_id"   , $member['id']              , 1);
				$this->ipsclass->my_setcookie('session_id', '0', -1 );
				
				$this->ipsclass->stronghold_set_cookie( $member['id'], $member['member_login_key'] );
				
				$this->ipsclass->boink_it($this->ipsclass->base_url.'&act=login&CODE=autologin&fromreg=1');
			}
		}
		else
		{
			// This is a COPPA user, so lets tell them they registered OK and redirect to the form.
			
			$this->ipsclass->DB->do_insert( 'validating', array (
												  'vid'         => $validate_key,
												  'member_id'   => $member['id'],
												  'real_group'  => $this->ipsclass->vars['member_group'],
												  'temp_group'  => $this->ipsclass->vars['auth_group'],
												  'entry_date'  => $time,
												  'coppa_user'  => $coppa,
												  'new_reg'     => 1,
												  'ip_address'  => $member['ip_address']
										)       );
			// ****************
			// Update by tuanhm 
			// On 06/08/2011
			//****************
			$url = "http://www.worldgames.vn/index.php?act=regportal&&CODE=wg";
			//$this->ipsclass->print->redirect_screen( $this->ipsclass->lang['cp_success'], 'act=Reg&amp;CODE=12' );
			$this->ipsclass->print->redirect_screen($url);
		}
 	}
 	
 	function show_terms_read($reg_code_err_msg="") {
 		//-----------------------------------------
		// INIT
		//-----------------------------------------
 		if($reg_code_err_msg) {
			$this->ipsclass->input = array_merge($this->ipsclass->input, $_SESSION);
			$_POST['act'] = 'termsread';
			$_POST = array_merge($_POST, $_SESSION);
		}		
		
		if( $this->ipsclass->vars['ipbli_usertype'] == 'email' )
		{
			$this->ipsclass->input['UserName'] = $this->ipsclass->input['members_display_name'];
		}
		
		$form_errors          = array();
		$coppa                = ($this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
		$in_username          = str_replace( '|', '&#124;' , $this->ipsclass->input['UserName'] );
		$in_password          = trim($this->ipsclass->input['PassWord']);
		$in_email             = strtolower( trim($this->ipsclass->input['EmailAddress']) );
		$banfilters           = array();
		$members_display_name = trim( $this->ipsclass->input['members_display_name'] );		
		

		//-----------------------------------------
		// Load ban filters
		//-----------------------------------------
		
		$this->ipsclass->DB->simple_construct( array( 'select' => '*', 'from' => 'banfilters' ) );
		$this->ipsclass->DB->simple_exec();
		
		while( $r = $this->ipsclass->DB->fetch_row() )
		{
			$banfilters[ $r['ban_type'] ][] = $r['ban_content'];
		}
		
		//-----------------------------------------
		// Check
		//-----------------------------------------
		
		//echo 'act : '.$_POST['act'];
		//echo '<br/>';
		
		//echo 'no reg : '.$this->ipsclass->vars['no_reg'];
		//echo '<br/>';
		//exit();
		
		if ($_POST['act'] == "")
		{
			$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'complete_form' ) );
		}
		
		if ($this->ipsclass->vars['no_reg'] == 1)
    	{
    		$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'reg_off' ) );
    	}
    	
    	
		//-----------------------------------------
		// Custom profile field stuff
		//-----------------------------------------
		
		require_once( ROOT_PATH.'sources/classes/class_custom_fields.php' );
    	$fields = new custom_fields( $this->ipsclass->DB );
    
    	$fields->cache_data  = $this->ipsclass->cache['profilefields'];
    	
    	$fields->init_data();
    	$fields->parse_to_save( 1 );
		
		//-----------------------------------------
		// Check...
		//-----------------------------------------
		
		if ( count( $fields->error_fields['empty'] ) )
		{
			foreach(  $fields->error_fields['empty'] as $cfield )
			{
				$form_errors['cfield_'.$cfield['pf_id']][$this->ipsclass->lang['err_complete_form']] = $this->ipsclass->lang['err_complete_form'];
			}
		}
		
		if ( count( $fields->error_fields['invalid'] ) )
		{
			foreach( $fields->error_fields['invalid'] as $cfield )
			{
				$form_errors['cfield_'.$cfield['pf_id']][$this->ipsclass->lang['err_invalid']] = $this->ipsclass->lang['err_invalid'];
			}
		}
		
		if ( count( $fields->error_fields['toobig'] ) )
		{
			foreach( $fields->error_fields['toobig'] as $cfield )
			{
				$form_errors['cfield_'.$cfield['pf_id']][$this->ipsclass->lang['err_cf_to_long']] = $this->ipsclass->lang['err_cf_to_long'];
			}
		}
		
		//-----------------------------------------
		// Remove multiple spaces in the username
		//-----------------------------------------
		
		$in_username = preg_replace( "/\s{2,}/", " ", $in_username );
		
		//-----------------------------------------
		// Remove linebreaks if set to
		//-----------------------------------------
		
		if( $this->ipsclass->vars['usernames_nobr'] )
		{
			$in_username = $this->ipsclass->my_br2nl( $in_username );
			$in_username = str_replace( "\n", "", $in_username );
			$in_username = str_replace( "\r", "", $in_username );
			
			$members_display_name = $this->ipsclass->my_br2nl( $members_display_name );
			$members_display_name = str_replace( "\n", "", $members_display_name );
			$members_display_name = str_replace( "\r", "", $members_display_name );
		}
		
		//-----------------------------------------
		// Remove 'sneaky' spaces
		//-----------------------------------------
		
		if ( $this->ipsclass->vars['strip_space_chr'] )
    	{
    		// use hexdec to convert between '0xAD' and chr
			$in_username          = str_replace( chr(160), ' ', $in_username );
			$in_username          = str_replace( chr(173), ' ', $in_username );
			$in_username          = str_replace( chr(240), ' ', $in_username );
			$members_display_name = str_replace( chr(160), ' ', $members_display_name );
			$members_display_name = str_replace( chr(173), ' ', $members_display_name );
			$members_display_name = str_replace( chr(240), ' ', $members_display_name );
		}
		
		//-----------------------------------------
		// Trim up..
		//-----------------------------------------
		
		$in_username = trim($in_username);
		
		//-----------------------------------------
		// Test unicode name too
		//-----------------------------------------
		
		$unicode_name  = preg_replace_callback('/&#([0-9]+);/si', create_function( '$matches', 'return chr($matches[1]);' ), $in_username);
		$unicode_name  = str_replace( "'" , '&#39;', $unicode_name );
		$unicode_name  = str_replace( "\\", '&#92;', $unicode_name );
		
		$unicode_dname = preg_replace_callback('/&#([0-9]+);/si', create_function( '$matches', 'return chr($matches[1]);' ), $members_display_name);
		$unicode_dname = str_replace( "'" , '&#39;', $unicode_dname );
		$unicode_dname = str_replace( "\\", '&#92;', $unicode_dname );
		
		//-----------------------------------------
		// Check the email address
		//-----------------------------------------
		
		$in_email = $this->ipsclass->clean_email($in_email);
		
		if ( ! $in_email OR strlen($in_email) < 6 )
		{
			$form_errors['email'][$this->ipsclass->lang['err_invalid_email']] = $this->ipsclass->lang['err_invalid_email'];
		}
		
		//-----------------------------------------
		// Test email address
		//-----------------------------------------
		
		// ---------------------------------------
		// Updated by hnmtuan on 06/08/2011
		// ---------------------------------------
		$this->ipsclass->input['EmailAddress']     = strtolower( trim($this->ipsclass->input['EmailAddress']) );
		$this->ipsclass->input['EmailAddress_two'] = $this->ipsclass->input['EmailAddress'];
		//$this->ipsclass->input['EmailAddress_two'] = strtolower( trim($this->ipsclass->input['EmailAddress_two']) );
		//$this->ipsclass->input['EmailAddress']     = strtolower( trim($this->ipsclass->input['EmailAddress']) );
		
		if( preg_match( "#[\;\#\n\r\*\'\"<>&\%\!\(\)\{\}\[\]\?\\/\s]#", $this->ipsclass->input['EmailAddress_two']) )
		{
			$form_errors['email'][$this->ipsclass->lang['reg_error_email_invalid']] = $this->ipsclass->lang['reg_error_email_invalid'];
		}
		else
		{		
			// ---------------------------------------
			// Updated by hnmtuan on 06/08/2011
			// ---------------------------------------
			/*
			if ( $in_email AND $this->ipsclass->input['EmailAddress_two'] != $in_email)
			{
				$form_errors['email'][$this->ipsclass->lang['reg_error_email_nm']] = $this->ipsclass->lang['reg_error_email_nm'];
			}
			* */
		}
		
		//-----------------------------------------
		// More unicode..
		//-----------------------------------------
		
		$len_u = preg_replace("/&#([0-9]+);/", "-", $in_username );
		$len_p = preg_replace("/&#([0-9]+);/", "-", $in_password );
		$len_d = preg_replace("/&#([0-9]+);/", "-", $members_display_name );
		
		//-----------------------------------------
		// Test dname
		//-----------------------------------------
		
		if ( $this->ipsclass->vars['auth_allow_dnames'] )
		{
			if ( ! $members_display_name OR strlen($len_d) < 3  OR strlen($len_d) > $this->ipsclass->vars['max_user_name_length'] )
			{
				$form_errors['dname'][$this->ipsclass->lang['reg_error_no_name']] = $this->ipsclass->lang['reg_error_no_name'];
			}
		}
		
		$this->ipsclass->vars['username_characters']=0;
		if( $this->ipsclass->vars['username_characters'] )
		{
			$check_against = preg_quote( $this->ipsclass->vars['username_characters'], "/" );
			
			if( !preg_match( "/^[".$check_against."]+$/i", $_POST['UserName'] ) && $this->ipsclass->vars['ipbli_usertype'] == 'username' )
			{
				$msg = str_replace( '{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg'] );
				$form_errors['username'][$msg] = $msg;
			}
			
			if( !preg_match( "/^[".$check_against."]+$/i", $_POST['members_display_name'] ) && $this->ipsclass->vars['auth_allow_dnames'] )
			{
				$msg = str_replace( '{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg'] );
				$form_errors['dname'][$msg] = $msg;
			}
		}
		
		//-----------------------------------------
		// Check for errors in the input.
		//-----------------------------------------
		
		if ( ! $in_username OR strlen($len_u) < 4  OR strlen($len_u) > $this->ipsclass->vars['max_user_name_length'] )
		{
			$form_errors['username'][$this->ipsclass->lang['reg_error_username_none']] = $this->ipsclass->lang['reg_error_username_none'];
		}
		
		if (! $in_password OR strlen($len_p) < 6  OR strlen($len_p) > $this->ipsclass->vars['max_user_name_length'] )
		{
			$form_errors['password'][$this->ipsclass->lang['reg_error_no_pass']] = $this->ipsclass->lang['reg_error_no_pass'];
		}
		
		// ---------------------------------------
		// Updated by hnmtuan on 06/08/2011
		// ---------------------------------------
		//$this->ipsclass->input['PassWord_Check'] = $in_password;
		
		/*
		if ($this->ipsclass->input['PassWord_Check'] != $in_password)
		{
			$form_errors['password'][$this->ipsclass->lang['reg_error_pass_nm']] = $this->ipsclass->lang['reg_error_pass_nm'];
		}
		* */
		
		//-----------------------------------------
		// CHECK 1: Any errors (missing fields, etc)?
		//-----------------------------------------				
		
		/*
		echo (count($form_errors));
		
		foreach ($form_errors as $key => $value){
			echo (''.$key.' - '.$value);
			echo ('<br/>');
		}
		
		exit();*/
		
		if ( count( $form_errors ) )
		{
			$this->show_page( $form_errors );
			return;
		}
				
		
 		//-----------------------------------------
		// USERNAME: Is this name already taken?
		//-----------------------------------------
		
		$this->ipsclass->DB->cache_add_query( 'login_getmember', array( 'username' => strtolower($in_username) ) );
		$this->ipsclass->DB->cache_exec_query();
		
		if ( $name_check['id'] )
		{
			$form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
		}
		
		//-----------------------------------------
		// USERNAME: Is this name already taken (display)?
		//-----------------------------------------
		
		if ( $this->ipsclass->vars['auth_allow_dnames'] )
		{
			if ( $this->ipsclass->vars['auth_dnames_nologinname'] )
			{
				$this->ipsclass->DB->build_query( array( 'select' => "members_display_name, id",
														 'from'   => 'members',
														 'where'  => "members_l_display_name='".strtolower($in_username)."'",
														 'limit'  => array( 0,1 ) ) );
													 
				$this->ipsclass->DB->exec_query();
				
				if ( $this->ipsclass->DB->get_num_rows() )
				{
					$form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
				}
			}
		}
		
		//-----------------------------------------
		// USERNAME: Special chars?
		//-----------------------------------------
		
		if ( $unicode_name != $in_username )
		{
			$this->ipsclass->DB->cache_add_query( 'login_getmember', array( 'username' => $this->ipsclass->DB->add_slashes(strtolower($unicode_name) ) ));
			$this->ipsclass->DB->cache_exec_query();
			
			$name_check = $this->ipsclass->DB->fetch_row();
			
			if ($name_check['id'])
			{
				$form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
			}
		}
		
		//-----------------------------------------
		// USERNAME: GUEST
		//-----------------------------------------
		
		if (strtolower($in_username) == 'guest')
		{
			$form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
		}
		
		//-----------------------------------------
		// USERNAME: Banned?
		//-----------------------------------------

		if ( is_array( $banfilters['name'] ) and count( $banfilters['name'] ) )
		{
			foreach ( $banfilters['name'] as $n )
			{
				$n = str_replace( '\*', '.*' ,  preg_quote($n, "/") );

				if ( $n AND preg_match( "/^{$n}$/i", $in_username ) )
				{
					$form_errors['username'][$this->ipsclass->lang['reg_error_username_taken']] = $this->ipsclass->lang['reg_error_username_taken'];
					break;
				}
			}
		}
		
		//-----------------------------------------
		// DNAME
		//-----------------------------------------
		
		if ( $this->ipsclass->vars['auth_allow_dnames'] )
		{
			//-----------------------------------------
			// Illegal characters
			//-----------------------------------------
			
			if ( preg_match( "#[\[\];,\|]#", str_replace('&#39;', "'", str_replace('&amp;', '&', $unicode_dname) ) ) )
			{
				$form_errors['dname'][$this->ipsclass->lang['reg_error_chars']] = $this->ipsclass->lang['reg_error_chars'];
			}
		
			//-----------------------------------------
			// DNAME: Is this name already taken?
			//-----------------------------------------
			
			$this->ipsclass->DB->cache_add_query( 'general_get_by_display_name', array( 'members_display_name' => strtolower($members_display_name) ) );
			$this->ipsclass->DB->cache_exec_query();
			
			$name_check = $this->ipsclass->DB->fetch_row();
			
			if ( $name_check['id'] )
			{
				$form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
			}
			
			//-----------------------------------------
			// DNAME: Check for existing LOG IN name.
			//-----------------------------------------
			
			if ( $this->ipsclass->vars['auth_dnames_nologinname'] )
			{
				$this->ipsclass->DB->build_query( array( 'select' => "members_display_name, id",
														 'from'   => 'members',
														 'where'  => "members_l_username='".strtolower($members_display_name)."'",
														 'limit'  => array( 0,1 ) ) );
													 
				$this->ipsclass->DB->exec_query();
				
				if ( $this->ipsclass->DB->get_num_rows() )
				{
					$form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
				}
			}
			
			//-----------------------------------------
			// DNAME: Special chars?
			//-----------------------------------------
			
			if ( $unicode_dname != $members_display_name )
			{
				$this->ipsclass->DB->cache_add_query( 'general_get_by_display_name', array( 'members_display_name' => $this->ipsclass->DB->add_slashes(strtolower($unicode_dname) ) ));
				$this->ipsclass->DB->cache_exec_query();
				
				$name_check = $this->ipsclass->DB->fetch_row();
				
				if ( $name_check['id'] )
				{
					$form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
				}
			}
			
			//-----------------------------------------
			// DNAME: Banned?
			//-----------------------------------------
			
			if ( is_array( $banfilters['name'] ) and count( $banfilters['name'] ) )
			{
				foreach ( $banfilters['name'] as $n )
				{
					$n = str_replace( '\*', '.*' ,  preg_quote($n, "/") );
					
					if ( $n AND preg_match( "/^{$n}$/i", $members_display_name ) )
					{
						$form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
						break;
					}
				}
			}
			
			//-----------------------------------------
			// DNAME: GUEST
			//-----------------------------------------
			
			if (strtolower($members_display_name) == 'guest')
			{
				$form_errors['dname'][$this->ipsclass->lang['reg_error_taken']] = $this->ipsclass->lang['reg_error_taken'];
			}
		}
		
		//-----------------------------------------
		// Is this email addy taken? CONVERGE THIS??
		//-----------------------------------------
		
		if ( $this->ipsclass->converge->converge_check_for_member_by_email( $in_email ) == TRUE )
		{
			$form_errors['email'][$this->ipsclass->lang['reg_error_email_taken']] = $this->ipsclass->lang['reg_error_email_taken'];
		}
		
        //-----------------------------------------
    	// Load handler...
    	//-----------------------------------------
    	
    	require_once( ROOT_PATH.'sources/handlers/han_login.php' );
    	$this->han_login           =  new han_login();
    	$this->han_login->ipsclass =& $this->ipsclass;
    	$this->han_login->init();
    	$this->han_login->email_exists_check( $email );
    	
    	if( $this->han_login->return_code != 'METHOD_NOT_DEFINED' AND $this->han_login->return_code != 'EMAIL_NOT_IN_USE' )
    	{
	    	$form_errors['email'][$this->ipsclass->lang['reg_error_email_taken']] = $this->ipsclass->lang['reg_error_email_taken'];
    	}
		
		//-----------------------------------------
		// Are they banned [EMAIL]?
		//-----------------------------------------
		
		if ( is_array( $banfilters['email'] ) and count( $banfilters['email'] ) )
		{
			foreach ( $banfilters['email'] as $email )
			{
				$email = str_replace( '\*', '.*' ,  preg_quote($email, "/") );
				
				if ( preg_match( "/^{$email}$/i", $in_email ) )
				{
					$form_errors['email'][$this->ipsclass->lang['reg_error_email_ban']] = $this->ipsclass->lang['reg_error_email_ban'];
					break;
				}
			}
		}
		
		//print_r ($form_errors);
		//exit();		
		
 		//-----------------------------------------
		// CHECK 2: Any errors (duplicate names, etc)?
		//-----------------------------------------
		
		
		if ( count( $form_errors ) )
		{
			$this->show_page( $form_errors );
			return;
		}
		
		
 		//-----------------------------------------
    	// INIT
    	//-----------------------------------------
    	
    	$final_errors = array();
    	
		if ( $this->ipsclass->vars['no_reg'] == 1 )
    	{
    		$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'reg_off' ) );
    	}
    	
    	$coppa = $this->ipsclass->my_getcookie( 'coppa' );
    	//$coppa = (isset($this->ipsclass->input['coppa_user']) AND $this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
    	
    	
    	if( $coppa == 'yes' )
    	{
	    	$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'awaiting_coppa' ) );
    	}
    	
    	$this->ipsclass->vars['username_errormsg'] = str_replace( '{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg'] );
    	    	
    	
    	if ( $this->ipsclass->member['id'] )
		{
			//-----------------------------------------
			// Log member out
			//-----------------------------------------
		
			require_once( ROOT_PATH.'sources/action_public/login.php' );
			$login           =  new login();
			$login->ipsclass =& $this->ipsclass;
			$login->do_log_out( 0 );
		}
			
		//-----------------------------------------
		// Continue
		//-----------------------------------------
		$_SESSION = array_merge($_SESSION, array('coppa_user'	=> $this->ipsclass->input['coppa_user'],
												 'UserName'		=> $this->ipsclass->input['UserName'],
												 'members_display_name'	=> $this->ipsclass->input['members_display_name'],
												 'day'			=> $this->ipsclass->input['day'],
												 'month'		=> $this->ipsclass->input['month'],
												 'year'			=> $this->ipsclass->input['year'],
												 'EmailAddress'	=> $this->ipsclass->input['EmailAddress'],
												 'EmailAddress_two' => $this->ipsclass->input['EmailAddress_two'],
												 'PassWord'		=> $this->ipsclass->input['PassWord'],
												 'PassWord_Check'	=> $this->ipsclass->input['PassWord_Check'],
												'country'   	  => $this->ipsclass->input['country'],
												 'city'			  => $this->ipsclass->input['city'],
												 'district' 	  => $this->ipsclass->input['district'],
												 'ward'			  => $this->ipsclass->input['ward'],
												 'address'		  => $this->ipsclass->input['address'],
												  'siteLocation'      => $this->ipsclass->input['siteLocation']
													)
								);
								

		// Set referer to redirect user back to their current page before they click on register link
		if(trim($this->ipsclass->input['referer'])) $_SESSION['referer'] = $this->ipsclass->input['referer']; 
		
 		require_once( ROOT_PATH.'sources/classes/class_custom_fields.php' );
    	$fields = new custom_fields( $this->ipsclass->DB );
    	
    	$fields->cache_data  = $this->ipsclass->cache['profilefields'];
    	
    	$fields->init_data();
    	$fields->parse_to_register();
    	
    	foreach( $fields->out_fields as $id => $data )
    	{
			$_SESSION['field_'.$id] = $this->ipsclass->input['field_'.$id];
    	}
    	
 		//-----------------------------------------
		// Clean out anti-spam stuffy
		//-----------------------------------------
		
		if ($this->ipsclass->vars['bot_antispam'])
		{
			// Set a new ID for this reg request...
			
			$regid = md5( uniqid(microtime()) );
			
			if( $this->ipsclass->vars['bot_antispam'] == 'gd' )
			{
				//-----------------------------------------
				// Get 6 random chars
				//-----------------------------------------
								
				$reg_code = strtoupper( substr( md5( mt_rand() ), 0, 6 ) );
			}
			else
			{
				//-----------------------------------------
				// Set a new 6 character numerical string
				//-----------------------------------------
				
				$reg_code = mt_rand(100000,999999);
			}
			
			// Insert into the DB
			
			$this->ipsclass->DB->do_insert( 'reg_antispam', array (
																	'regid'      => $regid,
																	'regcode'    => $reg_code,
																	'ip_address' => $this->ipsclass->input['IP_ADDRESS'],
																	'ctime'      => time(),
														)       );
		}
		
    	$cache = $this->ipsclass->DB->simple_exec_query( array( 'select' => '*', 'from' => 'conf_settings', 'where' => "conf_key='reg_rules'" ) );
    		
    	$text  = $cache['conf_value'] ? $cache['conf_value'] : $cache['conf_default'];
    	
    	/*
    	echo 'output in init state : '.$this->output;
    	echo '<br/>';
    	echo 'bot anitspam : '.$this->ipsclass->vars['bot_antispam'];
    	echo '<br/>';
    	* */
    	    	
    	$this->output .= $this->ipsclass->compiled_templates['skin_regportal']->show_terms( $this->ipsclass->my_nl2br($text), $coppa );
    	
    	/*
    	echo 'output after init state : '.$this->output;
    	echo '<br/>';
    	
    	exit();
    	*/
    	
 		if ($this->ipsclass->vars['bot_antispam'] == 'gd')
		{
			$this->output = str_replace( "<!--{REG.ANTISPAM}-->", $this->ipsclass->compiled_templates['skin_regportal']->bot_antispam_gd( $regid, $reg_code_err_msg ), $this->output );
		}
		else if ($this->ipsclass->vars['bot_antispam'] == 'gif')
		{
			$this->output = str_replace( "<!--{REG.ANTISPAM}-->", $this->ipsclass->compiled_templates['skin_regportal']->bot_antispam( $regid ), $this->output );
		}
		
		$this->page_title  = $this->ipsclass->lang['page_title'];
		$this->nav         = array( $this->ipsclass->lang['page_title'] );
 	}
 	
 	function show_search_result() {
 		require_once(KERNEL_PATH."search.class.php");
 		
 		$page = max(1,intval($this->ipsclass->input['page']));
		$keyword = str_replace('-',' ',$this->ipsclass->input['keyword']);
		$title = search::convertUnicode($keyword);//.' - Even Tim Kiem';	
		list($arrData,$total) = search::getContentToAPIGoogle($keyword,$page);
		$strHTML='';
		//print_r($arrData); exit;
		foreach($arrData as $k=>$itemWeb)
		{
			$strHTML.="<div class=\"rp-result-content\"><p><a target=\"_blank\" href=\"$itemWeb->unescapedUrl\" rel=\"nofollow\">$itemWeb->title</a></p><p>$itemWeb->content</p><p><span>$itemWeb->visibleUrl</span></p></div>";
		}
		$strUrlPage = $this->ipsclass->profile_url."search/%s%/".$this->ipsclass->input['keyword'].'.html';
		$strEvent 	= '';			
		$this->page_title = $keyword.' | '.$title.' - '.$this->ipsclass->lang['search_title'];
		list($strPage,$strResult) = search::getPagesLinks($total,$page,8,$strUrlPage,$strEvent,'',false);	
		
		$this->output = $this->ipsclass->compiled_templates['skin_regportal']->search_result_page($keyword, $strHTML, $strPage, $strResult);
 	}
 	
	//-----------------------------------------
	// Created by tuanhnm on 22/07/2011
	//-----------------------------------------    	
 	function my_show_page($form_errors=array()){
		$this->ipsclass->load_template('skin_intro');
		
		
		// Check login 		
		$this->output = $this->ipsclass->compiled_templates['skin_intro']->main_page();		
 		//$this->page_title  = $this->ipsclass->lang['page_title'];
		//$this->nav         = array( $this->ipsclass->lang['page_title'] );
		
		
		//print $this->ipsclass->skin['_wrapper'];
		
		print $this->output;
		
	}
	
	//-----------------------------------------
	// Created by tuanhnm on 22/07/2011
	//-----------------------------------------    	
 	function my_show_page_cpanel($form_errors=array()){
		
		$this->ipsclass->load_template('skin_regportal');
		
		
		//-----------------------------------------
    	// Check viewing permissions, etc
		//-----------------------------------------
		
		if ( ! $this->ipsclass->member['id'] )
		{
			$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'no_guests' ) );
		}
		
		$_member_ids = array();
		
		$friends[] = array();
		
		$comments[] = array();
		
		$sql_extra       = '';
		
		$member_id = intval( $this->ipsclass->member['id'] );	
		
		//$member_id = 16;
		
		$comment_perpage = 10;
		
		$start = intval( $this->ipsclass->input['st'] );
		
		$member = $this->personal_function_load_member( $member_id );
		
		$member = $this->personal_portal_set_information($member);					
		
		// Moved to here by Tuanhnm
		if ( $member['pp_setting_count_friends'] > 0 )
		{
			$member['_cache'] = $this->ipsclass->unpack_member_cache( $member['members_cache'] ); // Exact friends to this user					
			
			if ( is_array( $member['_cache']['friends'] ) AND count( $member['_cache']['friends'] ) )
			{
				foreach( $member['_cache']['friends'] as $id => $approved )
				{
					$id = intval( $id );			
					
					if ( $approved AND $id )
					{
						$_member_ids[] = $id;
					}
				}
			
				if ( is_array( $_member_ids ) AND count( $_member_ids ) )
				{
					$_max      = count( $_member_ids ) > $member['pp_setting_count_friends'] ? $member['pp_setting_count_friends'] : count( $_member_ids );
					$_rand     = array_rand( $_member_ids, $_max );
					$_final    = array();					
					
					if ( is_array( $_rand ) AND count( $_rand ) )
					{
						foreach( $_rand as $_id )
						{
							$_final[] = $_member_ids[ $_id ];
						}
					}
							
				
					if ( count( $_final ) )
					{
						$sql_extra = ' AND friends_friend_id IN (' . implode( ',', $_final ) . ')';
					}
				}
			}
			
			$query = 'pf.friends_member_id='.intval($member_id).' AND pf.friends_approved=1 '.$sql_extra;
			$this->ipsclass->DB->flush_query();
			$this->ipsclass->DB->build_query( array( 'select'   => 'pf.*',
												 'from'     => array( 'profile_friends' => 'pf' ),
												 'where'    => $query,
												 'add_join' => array( 0 => array( 'select' => 'me.*',
																				  'from'   => array( 'member_extra' => 'me' ),
																				  'where'  => 'me.id=pf.friends_friend_id',
																				  'type'   => 'left' ),
																				1 => array( 'select' => 'm.*',
																				'from'   => array( 'members' => 'm' ),
																				'where'  => 'm.id=pf.friends_friend_id',
																				'type'   => 'left' ), 
																				2 => array( 'select' => 'pp.*',
																				  'from'   => array( 'profile_portal' => 'pp' ),
																				  'where'  => 'pp.pp_member_id=m.id',
																				  'type'   => 'left' ) ) ) );
																				  
			$this->ipsclass->DB->exec_query();	
		
			while( $row = $this->ipsclass->DB->fetch_row() )
			{
				$row['_friends_added'] = $this->ipsclass->get_date( $row['friends_added'], 'SHORT' );
				$row['_avatar']        = $this->ipsclass->get_avatar( $row['avatar_location'], $this->ipsclass->member['view_avs'], $row['avatar_size'], $row['avatar_type'] );
				$row['_last_active']   = $this->ipsclass->get_date( $row['last_activity'], 'DATE' );
			
				if( $row['login_anonymous']{0} == '1' )
				{
					// Member last logged in anonymous
				
					if( $this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group'] OR $this->ipsclass->vars['disable_admin_anon'] )
					{
						$row['_last_active'] = $this->ipsclass->lang['private'];
					}
				}

				$row['_location'] = $row['location'] ? $row['location'] : $this->ipsclass->lang['no_info'];
			
				$row = $this->personal_portal_set_information( $row, 0, 0 );
			
				$row['members_display_name_short'] = $this->ipsclass->txt_truncate( $row['members_display_name'], 13 );
				
				$friends[] = $row;
			}			
		}
		
		//-----------------------------------------
		// Sort
		//-----------------------------------------
		
		ksort( $friends );
		
		//-----------------------------------------
		// Reinit
		//-----------------------------------------
		$sql_extra = '';
		
		//-----------------------------------------
		// Not my tab? So no moderation...
		//-----------------------------------------
		
		if (  ( $member_id != $this->ipsclass->member['id'] ) AND ( ! $this->ipsclass->member['g_is_supmod'] ) )
    	{
    		$sql_extra = ' AND comment_approved=1';
    	}
		
		//-----------------------------------------
		// Regenerate comments... by tuanhnm
		//-----------------------------------------
		$sql_extra = '';
		
		$this->ipsclass->DB->flush_query();
		
		$this->ipsclass->DB->build_query( array( 'select'   => 'pc.*',
												 'from'     => array( 'profile_comments' => 'pc' ),
												 'where'    => 'pc.comment_for_member_id='.$member_id . $sql_extra,
												 'order'    => 'pc.comment_date DESC',
												 'limit'    => array( $start, $comment_perpage ),
												 'add_join' => array( 0 => array( 'select' => 'm.name, m.members_display_name, m.login_anonymous',
																				  'from'   => array( 'members' => 'm' ),
																				  'where'  => 'm.id=pc.comment_by_member_id',
																				  'type'   => 'left' ),
																	  1 => array( 'select' => 'pp.*',
																				  'from'   => array( 'profile_portal' => 'pp' ),
																				  'where'  => 'pp.pp_member_id=m.id',
																				  'type'   => 'left' ),	
																	  2 => array( 'select' => 'me.*',
																				  'from'   => array( 'member_extra' => 'me' ),
																				  'where'  => 'me.id=pc.comment_by_member_id',
																				  'type'   => 'left' ) ) ) );
																				

		$this->ipsclass->DB->exec_query();
		
		while( $row = $this->ipsclass->DB->fetch_row() )
		{
			$row['_comment_date']   = $this->ipsclass->get_date( $row['comment_date'], 'SHORT' );
			$row['_avatar']         = $this->ipsclass->get_avatar( $row['avatar_location'], $this->ipsclass->member['view_avs'], $row['avatar_size'], $row['avatar_type'] );
			$row['_last_active']    = $this->ipsclass->get_date( $row['last_activity'], 'SHORT' );
			// Added by BabyWolf
			$row['name'] 			= strtolower($row['name']);
			
			if( $row['login_anonymous']{0} == '1' )
			{
				// Member last logged in anonymous
				
				if( $this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group'] OR $this->ipsclass->vars['disable_admin_anon'] )
				{
					$row['_last_active'] = $this->ipsclass->lang['private'];
				}
			}

			$row['comment_content'] = $this->ipsclass->txt_wordwrap( $row['comment_content'], '19', ' ' );
			
			$row = $this->personal_portal_set_information( $row, 0, 0 );
			
			$comments[] = $row;
		}
				
		// get total friends of a current user
		$member['total_friends'] = (count($friends) < 2) ? 0: count($friends);
		$member['approved_friends'] = $friends;	
		$member['total_comments'] =  (count($comments) < 2) ? 0: count($comments);
		$member['comments'] = $comments;
		
		//$member['members_display_name'] =  $this->ipsclass->member['members_display_name']
		
		// Check login 		
		$this->output = $this->ipsclass->compiled_templates['skin_regportal']->content_wg_temp2($member);		
 		//$this->page_title  = $this->ipsclass->lang['page_title'];
		//$this->nav         = array( $this->ipsclass->lang['page_title'] );
				
		//print $this->ipsclass->skin['_wrapper'];
		
		//print $this->output;
	}
	
	 	/**
 	* Sets the personal photos up
 	*
 	* @return	void
 	* @since	IPB 2.2.0.2006-7-31
 	*/
    function personal_portal_set_information($member, $noids=0, $use_parsed=1)
 	{
		return $this->ipsclass->member_set_information( $member, $noids, $use_parsed );
	}
	
	function personal_function_load_member( $member_id=0 )
 	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$query = '';
		
		//-----------------------------------------
		// What do we have?
		//-----------------------------------------
		
		if ( is_array( $member_id ) )
		{
			$query = 'm.id IN ('.implode( ',', $member_id ) . ')';
		}
		else
		{
			$query = 'm.id='.intval($member_id);
		}
		
		//-----------------------------------------
		// Load member
		//-----------------------------------------
	
		$this->ipsclass->DB->build_query( array( 'select'   => 'm.*',
												 'from'     => array( 'members' => 'm' ),
												 'where'    => $query,
												 'add_join' => array( 0 => array( 'select' => 'me.*',
																				  'from'   => array( 'member_extra' => 'me' ),
																				  'where'  => 'me.id=m.id',
																				  'type'   => 'left' ),
																	  1 => array( 'select' => 'pp.*',
																				  'from'   => array( 'profile_portal' => 'pp' ),
																				  'where'  => 'pp.pp_member_id=m.id',
																				  'type'   => 'left' ),
														   			  2 => array( 'select' => 'g.*',
																				  'from'   => array( 'groups' => 'g' ),
																				  'where'  => 'g.g_id=m.mgroup',
																				  'type'   => 'left' ),
																	  3 => array( 'select' => 's.location_1_id, s.location_2_id, s.location_1_type, s.location_2_type, s.running_time, s.location as sesslocation',
																	 			  'from'   => array( 'sessions' => 's' ),
																				  'where'  => "s.member_id=m.id",
																				  'type'   => 'left' ),
																	  4 => array( 'select' => 'pc.*',
																				  'from'   => array( 'pfields_content' => 'pc' ),
																				  'where'  => 'pc.member_id=m.id',
																				  'type'   => 'left' ) ) ) );
		$this->ipsclass->DB->exec_query();	
		
		if ( is_array( $member_id ) )
		{
			while( $row = $this->ipsclass->DB->fetch_row() )
			{
				$member[ $row['id'] ] = $row;
			}
		}
		else
		{
			$member = $this->ipsclass->DB->fetch_row();
		
			$member['pp_setting_count_visitors'] = ( $member['pp_setting_count_visitors'] != 0 ) ? $member['pp_setting_count_visitors'] : 5;
			$member['pp_setting_count_comments'] = ( $member['pp_setting_count_comments'] != 0)  ? $member['pp_setting_count_comments'] : 5;
			$member['pp_setting_count_friends']  = ( $member['pp_setting_count_friends'] != 0 )  ? $member['pp_setting_count_friends']  : 5;
		}
		
		return $member;
	}
	
	//-----------------------------------------
	// Created by tuanhnm on 22/07/2011
	//-----------------------------------------    	
 	function my_show_page_profile($form_errors=array()){
		$this->ipsclass->load_template('skin_regportal');
		
		//-----------------------------------------
    	// Check viewing permissions, etc
		//-----------------------------------------
		
		
		if ( ! $this->ipsclass->member['id'] )
		{
			$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'no_guests' ) );
		}
		
		$member_id = intval( $this->ipsclass->member['id'] );
		
		// Get information member
			
		
		$member = $this->personal_function_load_member( $member_id );
		
		$member = $this->personal_portal_set_information($member);
                
                $this->ipsclass->member = $member;
                //echo $member['field_16'];
                //var_dump($this->ipsclass->member);
                //exit();
                //var_dump($this->ipsclass->member = $member);
                //exit();
		/*
		$member['address_mem'] = 'khong ton tai field nay trong csdl';
		$member['joined_mem'] =$this->ipsclass->get_date($member['joined'], 'JOINED' );;
		$member['nums_posts_mem'] = $member['posts'];
		$member['friends_mem'] =  count($this->ipsclass->member['_cache']['friends']);
		$member['post_per_day_mem'] = '5.17';
		$member['attachs_mem'] = '0';
		$member['reads_mem'] = '0';
		$member['write_mem'] = '';
		*/
		
		
		// Check login 		
		//$this->output = $this->ipsclass->compiled_templates['skin_regportal']->content_pf();		
		$this->output = $this->ipsclass->compiled_templates['skin_regportal']->content_pf_temp($member);		
 		//$this->page_title  = $this->ipsclass->lang['page_title'];
		//$this->nav         = array( $this->ipsclass->lang['page_title'] );
		
		
		//print $this->ipsclass->skin['_wrapper'];
		
		//print $this->output;
	}
    
    function my_show_page_search($form_errors=array()){
        $this->ipsclass->load_template('skin_regportal');
		
		//-----------------------------------------
    	// Check viewing permissions, etc
		//-----------------------------------------
		
        /*
		if ( ! $this->ipsclass->member['id'] )
		{
			$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'no_guests' ) );
		}
		
		$member_id = intval( $this->ipsclass->member['id'] );*/
		
		// Get information member
			
		
		//$member = $this->personal_function_load_member( $member_id );
		
		//$member = $this->personal_portal_set_information($member);
		
		/*$member['address_mem'] = 'khong ton tai field nay trong csdl';
		$member['joined_mem'] =$this->ipsclass->get_date($member['joined'], 'JOINED' );;
		$member['nums_posts_mem'] = $member['posts'];
		$member['friends_mem'] =  count($this->ipsclass->member['_cache']['friends']);
		$member['post_per_day_mem'] = '5.17';
		$member['attachs_mem'] = '0';
		$member['reads_mem'] = '0';
		$member['write_mem'] = '';
		*/
		
		
		// Check login 		
		//$this->output = $this->ipsclass->compiled_templates['skin_regportal']->content_pf();		
		//$this->output = $this->ipsclass->compiled_templates['skin_regportal']->content_pf_temp($member);
        $this->output = $this->ipsclass->compiled_templates['skin_regportal']->search_friend($temp='');			
 		//$this->page_title  = $this->ipsclass->lang['page_title'];
		//$this->nav         = array( $this->ipsclass->lang['page_title'] );
		
		
		//print $this->ipsclass->skin['_wrapper'];
		
		//print $this->output;
    }
 	
 	function show_page($form_errors=array()) {
 		//-----------------------------------------
    	// INIT
    	//-----------------------------------------   
    	
 		// Check if member have already login, redirect them to their user panel page
		if($this->ipsclass->member['id'])
			$this->ipsclass->boink_it($this->ipsclass->vars['my_url']."/index.php?act=UserCP&CODE=00");			
	
    	$final_errors = array();
    	
		if ( $this->ipsclass->vars['no_reg'] == 1 )
    	{
    		$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'reg_off' ) );
    	}
    	
    	$coppa = $this->ipsclass->my_getcookie( 'coppa' );
    	//$coppa = (isset($this->ipsclass->input['coppa_user']) AND $this->ipsclass->input['coppa_user'] == 1) ? 1 : 0;
    	
    	if( $coppa == 'yes' )
    	{
	    	$this->ipsclass->Error( array( 'LEVEL' => 1, 'MSG' => 'awaiting_coppa' ) );
    	}
    	
    	$this->ipsclass->vars['username_errormsg'] = str_replace( '{chars}', $this->ipsclass->vars['username_characters'], $this->ipsclass->vars['username_errormsg'] );   
    
    	
    	//-----------------------------------------
    	// Do we have another URL that one needs
    	// to visit to register?
    	//-----------------------------------------
    	
    	$this->login_method = $this->ipsclass->DB->build_and_exec_query( array( 'select' => '*', 'from' => 'login_methods', 'where' => 'login_enabled=1' ) );
    	
    	if ( $this->login_method['login_register_url'] )
    	{
    		$this->ipsclass->boink_it( $this->login_method['login_register_url'] );
    		exit();
    	}    	
    	//-----------------------------------------
    	// Continue...
    	//-----------------------------------------
    	
    	if ( $this->ipsclass->vars['reg_auth_type'] )
    	{
	    	if ( $this->ipsclass->vars['reg_auth_type'] == 'admin_user' OR $this->ipsclass->vars['reg_auth_type'] == 'user' )
	    	{
    			$this->ipsclass->lang['std_text'] .= "<br />" . $this->ipsclass->lang['email_validate_text'];
			}
    		
    		//-----------------------------------------
    		// User then admin?
    		//-----------------------------------------
    		
    		if ( $this->ipsclass->vars['reg_auth_type'] == 'admin_user' )
    		{
    			$this->ipsclass->lang['std_text'] .= "<br />" . $this->ipsclass->lang['user_admin_validation'];
    		}
    		
    		if ( $this->ipsclass->vars['reg_auth_type'] == 'admin' )
    		{
	    		$this->ipsclass->lang['std_text'] .= "<br />" . $this->ipsclass->lang['just_admin_validation'];
    		}
    	}
    	
    	//-----------------------------------------
		// Custom profile fields stuff
		//-----------------------------------------
		
		$required_output = "";
		$optional_output = "";
		
		require_once( ROOT_PATH.'sources/classes/class_custom_fields.php' );
    	$fields = new custom_fields( $this->ipsclass->DB );
    	
    	$fields->cache_data  = $this->ipsclass->cache['profilefields'];
    	
    	$fields->init_data();
    	$fields->parse_to_register();
    	
    	foreach( $fields->out_fields as $id => $data )
    	{
	    	$error = "";
	    	
    		if ( $fields->cache_data[ $id ]['pf_not_null'] == 1 )
			{
				$ftype = 'required_output';
			}
			else
			{
				$ftype = 'optional_output';
			}
			
			if( isset($form_errors['cfield_'.$id]) AND count( $form_errors['cfield_'.$id] ) )
			{
				$error = implode( "<br />", $form_errors['cfield_'.$id] );
			}
    		
    		if ( $fields->cache_data[ $id ]['pf_type'] == 'drop' )
			{
				$form_element = $this->ipsclass->compiled_templates['skin_regportal']->field_dropdown( 'field_'.$id, $data, $error );
			}
			else if ( $fields->cache_data[ $id ]['pf_type'] == 'area' )
			{
				$data = $this->ipsclass->input['field_'.$id] ? $this->ipsclass->input['field_'.$id] : $data;
				$data = $this->ipsclass->my_br2nl( $data );			
				$form_element = $this->ipsclass->compiled_templates['skin_regportal']->field_textarea( 'field_'.$id, $data, $error );
			}
			else
			{
				$data = isset($this->ipsclass->input['field_'.$id]) ? $this->ipsclass->input['field_'.$id] : $data;
				$form_element = $this->ipsclass->compiled_templates['skin_regportal']->field_textinput( 'field_'.$id, $data, $error );
			}
			
			${$ftype} .= $this->ipsclass->compiled_templates['skin_regportal']->field_entry( $fields->field_names[ $id ], $fields->field_desc[ $id ], $form_element, $id, $error );
    	}
    	
    	//-----------------------------------------
    	// ERROR CHECK
    	//-----------------------------------------
    	
    	if ( isset($form_errors['general']) AND is_array( $form_errors['general'] ) AND count( $form_errors['general'] ) )
    	{
    		$this->output .= $this->ipsclass->compiled_templates['skin_regportal']->errors( implode( "<br />", $form_errors['general'] ) );
    	}
    	
    	//-----------------------------------------
    	// Other errors
    	//-----------------------------------------
    	
    	$final_errors = array( 'username' => NULL, 'dname' => NULL, 'password' => NULL, 'email' => NULL );
    	
    	foreach( array( 'username', 'dname', 'password', 'email' ) as $thing )
    	{
			if ( isset($form_errors[ $thing ]) AND is_array( $form_errors[ $thing ] ) AND count( $form_errors[ $thing ] ) )
			{
				$final_errors[ $thing ] = implode( "<br />", $form_errors[ $thing ] );
			}
		}
		
		$this->ipsclass->input['UserName'] 				= isset($this->ipsclass->input['UserName']) 			? $this->ipsclass->input['UserName'] 				: '';
		$this->ipsclass->input['PassWord'] 				= isset($this->ipsclass->input['PassWord']) 			? $this->ipsclass->input['PassWord'] 				: '';
		$this->ipsclass->input['EmailAddress'] 			= isset($this->ipsclass->input['EmailAddress']) 		? $this->ipsclass->input['EmailAddress'] 			: '';
		$this->ipsclass->input['EmailAddress_two']		= isset($this->ipsclass->input['EmailAddress_two'])		? $this->ipsclass->input['EmailAddress_two']		: '';
		$this->ipsclass->input['PassWord_Check'] 		= isset($this->ipsclass->input['PassWord_Check']) 		? $this->ipsclass->input['PassWord_Check'] 			: '';
		$this->ipsclass->input['members_display_name'] 	= isset($this->ipsclass->input['members_display_name'])	? $this->ipsclass->input['members_display_name']	: '';
		
 		//-----------------------------------------
		// Format the birthday drop boxes..
		//-----------------------------------------
		
		$date = getdate();
		
		$day  = "<option value='0'>--</option>";
		$mon  = "<option value='0'>--</option>";
		$year = "<option value='0'>--</option>";
		
		for ( $i = 1 ; $i < 32 ; $i++ )
		{
			$day .= "<option value='$i'>$i</option>";
		}
		
		for ( $i = 1 ; $i < 13 ; $i++ )
		{
			$mon .= "<option value='$i'>{$this->ipsclass->lang['month'.$i]}</option>";
		}
		
		$i = $date['year'] - 1;
		$j = $date['year'] - 100;
		
		for ( $i ; $j < $i ; $i-- )
		{
			$year .= "<option value='$i'>$i</option>";
		}
		$address  = "<option value='0'>--</option>";
 		$this->ipsclass->DB->simple_construct( array( 'select' => '*', 'from' => 'location','order'	=> 'location_name'));
		$this->ipsclass->DB->simple_exec();
		while( $site = $this->ipsclass->DB->fetch_row() )
		{
			if($site['location_level']==0)$address .= "<option value='{$site['location_id']}|{$site['location_name']}'>{$site['location_name']}</option>";
			else $option .= "|{$site['location_parent']}~{$site['location_id']}~{$site['location_name']}| ";
		}
		
		$this->ipsclass->DB->simple_construct( array( 'select' => '*', 'from' => 'sites','where'=>'site_location=1'));
		$this->ipsclass->DB->simple_exec();
		$locat = "<option value='all'>--</option>";
		while( $site = $this->ipsclass->DB->fetch_row() )
		{
			$locat  .= "<option value='{$site['site_name']}'>{$site['site_name']}</option>";
		}
						    		
    	$regForm .= $this->ipsclass->compiled_templates['skin_regportal']->ShowForm( array( 'TEXT' => $this->ipsclass->lang['std_text'], 
    																						'coppa_user' => $coppa,
    																						'day' => $day,
    																						'month' => $mon,
    																						'year'	=> $year,
    																						'address'=>$address,'opt'=>$option,'location'=>$locat), $final_errors );
    	
    	//-----------------------------------------
    	// Replace elements
    	//-----------------------------------------
    	
    	if ($required_output != "")
		{
			$regForm = str_replace( "<!--{REQUIRED.FIELDS}-->", "\n".$required_output, $regForm );
		}
		
		if ($optional_output != "")
		{
			$regForm = str_replace( "<!--{OPTIONAL.FIELDS}-->", "\n".$optional_output, $regForm );
		}
		
		if ( USE_MODULES == 1 )
		{
			$this->modules->register_class($this);
    		$this->modules->on_register_form();
   		}
   		
 		
 		$this->output = $this->ipsclass->compiled_templates['skin_regportal']->main_page($regForm);
 		$this->page_title  = $this->ipsclass->lang['page_title'];
		$this->nav         = array( $this->ipsclass->lang['page_title'] );
 	}
}

?>
